package com.sky.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PasswordEncryptor {
    private static final Logger logger = LoggerFactory.getLogger(PasswordEncryptor.class);

    // 加密密码
    public static String encryptPassword(String plainTextPassword) {
        if (plainTextPassword == null) {
            throw new IllegalArgumentException("密码不能为空");
        }
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hash = md.digest(plainTextPassword.getBytes());
            StringBuilder hexString = new StringBuilder();
            for (byte b : hash) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) hexString.append('0');
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            logger.error("Error encrypting password", e);
            throw new RuntimeException("Error encrypting password", e);
        }
    }

    // 验证密码
    public static boolean checkPassword(String plainTextPassword, String hashedPassword) {
        if (plainTextPassword == null || hashedPassword == null) {
            return false;
        }
        String newHashedPassword = encryptPassword(plainTextPassword);
        return newHashedPassword.equals(hashedPassword);
    }
}